package com.caits.lbs.framework.utils;

import org.apache.logging.log4j.LogManager;

import com.caits.lbs.framework.bean.common.ApiResult;



public class ApiResultBase64Util {

    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(ApiResultBase64Util.class);

    /**
     * @throws
     * @Title: encode
     * @Description: 返回结果加密
     * @param: @param apiResult
     * @param: @return
     * @return: String
     */
    public static String encode(ApiResult apiResult, String apiAuthKey) {
        String seqNo = null;
        if (apiResult.getHead() != null) {
        	seqNo = apiResult.getHead().getSequenceCode();
        }
        return formatResult(apiResult, apiAuthKey, seqNo);
    }


    public static String formatResult(ApiResult apiResult, String apiAuthKey, String seqNo) {
        return formatResult(JsonUtilAlibaba.getJsonString(apiResult), apiAuthKey, seqNo);
    }


    public static String formatResult(String result, String apiAuthKey, String seqNo) {
        String rs = result;
        try {

            //获取 md5签名
            ApiResult apiResult = JsonUtilAlibaba.getApiResult(result);
            apiResult.setSign(apiAuthKey);
            if (apiResult.getHead() != null) {
                apiResult.getHead().setSequenceCode(seqNo);
            }

            //返回给APP的参数需要 body 为null是 需要创建
            if (apiResult.getBody() == null) {
                apiResult.setBody(new Object());
            }
            //  md5
            String md5Str = MD5.encode(JsonUtilAlibaba.getJsonString(apiResult));
            apiResult.setSign(md5Str);

            rs = JsonUtilAlibaba.getJsonString(apiResult);
        } catch (Exception e) {
            logger.error("返回结果 格式化结果异常！e:{}", e);
        }
        return rs;
    }


    /**
     * 替换图片url 改为https
     *
     * @param rs
     * @return
     */
    public static String replaceImageUrl2Https(String rs) {
        try {
            logger.info("替换图片url前json:{}"+rs);
            String pattern = "http://(.{0,20})appimgs\\.";
            rs = rs.replaceAll(pattern, "https://$1appimgs.");
            logger.debug("替换图片url后json:{}"+ rs);
        } catch (Exception e) {
            logger.info("替换图片url异常！e:{}", e);
            logger.error("替换图片url异常！e:{}", e);
        }
        return rs;
    }
}
